package edu.chl.da.ejb.persistency;

import edu.chl.da.ejb.core.Account;
import edu.chl.da.ejb.core.Account_;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Jakob
 */
@Stateless
public class AccountFacade implements IAccountFacade {
    @PersistenceContext(unitName = "airline_pu")
    private EntityManager em;

    @Override
    public Account find(Object id) {
        return em.find(Account.class, id);
    }

    @Override
    public Account findByUsernameAndPassword(String username, String password) {
        CriteriaBuilder qbuilder = em.getCriteriaBuilder();
        CriteriaQuery cq = qbuilder.createQuery();
        Root<Account> root = cq.from(Account.class);

        Predicate pred = qbuilder.and(qbuilder.equal(root.get(Account_.username), username)
                , qbuilder.equal(root.get(Account_.password), password));
        
        cq.where(pred);

        TypedQuery<Account> q = em.createQuery(cq);
        return q.getSingleResult();
    }
}
